<template>
    <div>
      <van-field
        :class="fieldClass"
        v-model="text"
        v-bind="$attrs"
        readonly
        is-link
        :name="$attrs.name"
        @click="show = !show"
      >
      </van-field>
      <van-popup v-model="show" round position="bottom" get-container="body">
        <van-picker
          :columns="columns"
          show-toolbar
          :value-key="labelKey"
          :title="$attrs.label"
          :default-index="index"
          :loading="$attrs.loading"
          @cancel="show = !show"
          @confirm="onConfirm"
        ></van-picker>
      </van-popup>
    </div>
  </template>
   
  <script>
  export default {
    name: "van-select",
    props: {
        //传入的对象数组，支持异步更新，内部van-field的显示值和van-picker的选项也会自动更新
      columns: {
        type: Array,
      },
      //传入的默认值，支持异步更新，内部van-field的显示值也会自动更新
      modelValue: {
        type: [String, Number],
        default: "",
      },
      // field块自定义类名
      fieldClass: {
        type: String,
        default: "",
      },
      // 选项对象中，选项文字对应的键名
      labelKey: {
        type: String,
        default: "label",
      },
      // 选项对象中，选项值对应的键名
      valueKey: {
        type: String,
        default: "value",
      },
      searchKey:{
        type: String,
        default: "",
      }
    },
    data() {
      return {
        show: false,
        value: "",
        text: "",
        index: 0,
      };
    },
    created() {
      this.echo() // 初始值默认存在
    },
    watch: {
      value(newVal) {
        console.log("🚀 ~ value ~ newVal:", newVal)
        this.$emit("update:modelValue", newVal);
      },
      /**
       * @description: 初始值异步更新，触发value更新
       */
      modelValue() {
        this.echo();
      },
      /**
       * @description: columns异步更新，触发value更新
       */
      columns() {
        this.echo();
      },
    },
   
    methods: {
      onConfirm(value) {
        this.text = value[this.labelKey];
        this.value = value[this.valueKey];
        this.show = !this.show;
        this.$emit("valueObject", {...value,key:this.searchKey});

      },
      echo() {
        this.columns.some((item, index) => {
          if (item[this.valueKey] === this.modelValue) {
            this.text = this.columns[index][this.labelKey];
            this.index = index;
            return true;
          } else {
            return false;
          }
        });
      },
    },
  };
  </script>